package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BaseBusinessException;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

	@Autowired
	private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {
		CreateOrderContext createOrderContext = (CreateOrderContext) context;

		List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
		List<Long> buyProductIds = createOrderContext.getBuyProductIds();
		if (CollectionUtils.isEmpty(buyProductIds)) {
			buyProductIds = cartProductDtoList.stream().map(CartProductDto::getProductId).collect(Collectors.toList());
			//buyProductIds = cartProductDtoList.stream().map(p -> p.getProductId()).collect(Collectors.toList());
		}
		// 对商品进行排序，也可以不排序
		buyProductIds.sort(Long::compareTo);

		// 锁定库存
		List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);

		if (CollectionUtils.isEmpty(stockList)) {
			throw new BizException("库存未初始化！");
		}

		if (stockList.size() != buyProductIds.size()) {
			throw new BizException("部分商品库存未初始化！");
		}

		// 扣减商品库存
		for (CartProductDto cartProductDto : cartProductDtoList) {

			// 判断商品的库存是否充足
			Stock stockOfCurrentProduct = stockMapper.selectStock(cartProductDto.getProductId());
			if (cartProductDto.getProductNum() > stockOfCurrentProduct.getStockCount()) {
				throw new BizException(cartProductDto.getProductName() + "库存不足！");
			}

			// 判断商品数量是否超过限购数量
			if (cartProductDto.getProductNum() > stockOfCurrentProduct.getRestrictCount()) {
				throw new BizException(cartProductDto.getProductName() + "超出限购数量!");
			}

			Stock stock = new Stock();
			stock.setItemId(cartProductDto.getProductId());
			stock.setLockCount(cartProductDto.getProductNum().intValue());
			stock.setStockCount(-cartProductDto.getProductNum());

			// 数据库中更新库存
			stockMapper.updateStock(stock);
		}

		return true;
	}
}